package com.test.ssh.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.test.ssh.dao.UserDao;
import com.test.ssh.entity.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao{

	@Override
	public User getByUserName(String name) {
		//HQL
		/*return getHibernateTemplate().execute(new HibernateCallback<User>() {

			@Override
			public User doInHibernate(Session session) throws HibernateException {
				String hql="from User where name = ?";
				Query query = session.createQuery(hql);
				query.setParameter(0, name);
				List<User> resultList = query.getResultList();
				return resultList!=null&&resultList.size()>0?resultList.get(0):null;
			}
		});*/
		
		//Criteria
		DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		dc.add(Restrictions.eq("name", name));
		List<User> resultList = (List<User>) getHibernateTemplate().findByCriteria(dc);
		return resultList!=null&&resultList.size()>0?resultList.get(0):null;
	}

	@Override
	public void save(User user) {
		getHibernateTemplate().save(user);
		
	}

}
